<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2020/09/15
 * Time: 15:39
 * @link http://www.lmterp.cn
 */

namespace app\admin\controller\wms;

use app\admin\controller\BaseController;
use app\common\library\Tools;
use app\common\model\Account;
use app\common\model\AccountPlatform;
use app\common\model\Product;
use app\common\model\ProductPlatformSku;
use app\common\model\ProductStore;
use app\common\service\product\PlatformService;

class PlatformController extends BaseController
{
    /**
     * 平台sku列表
     * @return string|array
     * @date 2020/09/15
     * @author longli
     */
    public function index()
    {
        if($this->request->isAjax())
        {
            $pskus = $this->search();
            return apiResponsePage($pskus);
        }
        $this->assign('select_product', [
            'platform_sku' => '平台SKU',
            'sku' => 'SKU',
        ]);
        $this->assign('platform', AccountPlatform::getAll());
        $this->assign('account', Account::getAll());
        $this->assign("status", ProductPlatformSku::$STATUS);
        $this->assign('create_date', [-1 => '昨天', 0 => '今天', -6 => '7天前', -59 => '60天前']);
        $this->assign('sort', ['product_id' => '生成时间', 'name_ch' => '名称']);
        return $this->fetch("index");
    }

    /**
     * 搜索
     * @return ProductPlatformSku[]|\think\Paginator
     * @throws \think\exception\DbException
     * @date 2020/09/15
     * @author longli
     */
    private function search()
    {
        $data = $this->request->request();
        $sort = "pid desc";
        if(!empty($data['sort'])) $sort = "p.{$data['sort']}";
        $model = ProductPlatformSku::order($sort)->with(["store", "account", "product"]);
        if(!empty($data['account_id']))
        {
            $model->whereIn("account_id", function($query)use($data)
            {
                $query->table(Account::getTable())->where("account_id", $data['account_id'])->field("account_id");
            });
        }
        if(!empty($data['category_id']))
        {
            $model->whereIn("product_id", function($query)use($data)
            {
                $query->table(Product::getTable())->whereIn("category_id", $data['category_id'])->field("product_id");
            });
        }
        if(isset($data['create_date']))
        {
            $model->where($this->parseScopeDateToWhere("create_time", intval($data['create_date'])));
        }
        $this->searchModel($model, [
            'times' => ['start_date' => 'create_time'],
            'eq' => ['account_id'],
            'like' => ['sku', 'platform_sku'],
        ]);
        return $model->paginate($this->getPageSize());
    }

    /**
     * 再次生成平台SKU
     * @date 2020/09/15
     * @author longli
     */
    public function readd()
    {
        $pid = $this->request->request("pid");
        if(empty($pid)) $this->error('参数错误');
        PlatformService::getInstance()->generateSkuByPid($pid)
            ? $this->success('生成成功')
            : $this->error('生成失败');
    }

    /**
     * 删除平台SKU
     * @date 2020/09/15
     * @author longli
     */
    public function delete()
    {
        $pid = $this->request->request("ids");
        if(empty($pid)) $this->error('参数错误');
        ProductPlatformSku::destroy($pid);
        $this->success('删除成功');
    }

    /**
     * 导出文件
     * @date 2020/09/13
     * @author longli
     */
    public function export()
    {
        $ids = $this->request->request("ids");
        $startDate = $this->request->request("start_date");
        $accountId = $this->request->request("account_id");
        $platform = $this->request->request("platform");
        if(empty($ids) && empty($startDate)) $this->error("非法导出，请检查导出条件");
        if(!empty($platform))
        {
            $platform = AccountPlatform::get(['name' => $platform]);
            if(empty($platform)) $this->error("选择的平台不存在，请检查");
            $accountId = array_column($platform->account->toArray(), 'account_id');
        }
        $condition = [];
        if(!empty($ids)) $condition[] = ['sku.pid', 'in', $ids];
        if(!empty($startDate)) $condition = array_merge($condition, $this->parseLayuiRangeDate("sku.create_time", $startDate));
        if(!empty($accountId)) $condition[] = ['sku.account_id', 'in', $accountId];

        $skuExport = new \app\common\service\export\PlatformSku();
        $file = $skuExport->runExcel($condition);
        $this->success("导出成功", "", ["src" => urlencode($file)]);
    }

    /**
     * 导入商品
     * @date 2020/09/13
     * @author longli
     */
    public function import()
    {
        $file = $this->request->request("path");
        if(Tools::startWith($file, '/')) $file = \Env::get("root_path") . "public{$file}";
        $skuImport = new \app\common\service\import\PlatformSku($file);
        try
        {
            $skuImport->run();
            return apiResponse(\app\common\status\BaseStatus::CODE_NORMAL, [], '导入成功');
        }catch(\RuntimeException $e)
        {
            $this->error($e->getMessage());
        }
    }

    /**
     * 生成平台sku
     * @date 2020/09/15
     * @author longli
     */
    public function generatesku()
    {
        $accountId = $this->request->request("account_id");
        $productId = $this->request->request("product_id");
        $storeId = $this->request->request("store_id");
        if(empty($accountId) || (empty($productId) && empty($storeId))) $this->error("非法请求");
        if(!empty($productId))
        {
            $t = ProductStore::field("store_id")
                ->where("product_id", "in", $productId)
                ->select()->toArray();
            $storeId = array_column($t, 'store_id');
        }
        if(empty($storeId)) $this->error("未选择要生成SKU的商品");
        PlatformService::getInstance()->generateSkuByStoreId($accountId, $storeId)
            ? $this->success("生成成功")
            : $this->error("生成失败");
    }
}